/*
  This file is part of 'Trivial chess'.

  'Trivial chess' is free software: you can redistribute it and/or modify
  it under the terms of the GNU General Public License as published by
  the Free Software Foundation, either version 3 of the License, or
  (at your option) any later version.

  'Trivial chess' is distributed in the hope that it will be useful,
  but WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  GNU General Public License for more details.

  You should have received a copy of the GNU General Public License
  along with 'Trivial chess'.  If not, see <http://www.gnu.org/licenses/>.
*/

/* SVN FILE: $Id$ */
/**
 * @author         $Author$
 * @version        $Rev$
 * @lastrevision   $Date$
 * @filesource     $URL$
 */

#ifndef LEAPERAFFECTVECABSTRACT_H_
#define LEAPERAFFECTVECABSTRACT_H_

#include <boost/cstdint.hpp>
#include <boost/array.hpp>

#include "AffectAbstract.h"

template<class LeaperAffectVec, class Br, class Sq, class Mn, class Vc, typename Int = int8_t>
class LeaperAffectVecAbstract
	: public AffectAbstract<LeaperAffectVec,Br,Sq,Mn> {

public:
	typedef Sq Square;
	typedef Vc SquareVector;
	typedef typename SquareVector::FileScalar FileScalar;
	typedef typename SquareVector::RankScalar RankScalar;
private:

#	define _(_F,_R) SquareVector(FileScalar(_F),RankScalar(_R))

	static const boost::array<const SquareVector, 8> KNIGHT_VECTORS() {

		const boost::array<const SquareVector, 8> ret = {{
				_(2,1),_(2,-1),_(-2,1),_(-2,-1),
				_(1,2),_(1,-2),_(-1,2),_(-1,-2)
			}};

		return ret;
	}
	static const boost::array<const SquareVector, 8> KING_VECTORS() {
		const boost::array<const SquareVector, 8> ret = {{
				_(1,1),_(1,-1),_(-1,1),_(-1,-1),
				_(1,1),_(1,-1),_(-1,1),_(-1,-1)
			}};
		return ret;
	}
#		undef _

public:
	LeaperAffectVecAbstract<LeaperAffectVec,Br,Sq,Mn,Vc,Int>() : i(-1) {}

	LeaperAffectVecAbstract<LeaperAffectVec,Br,Sq,Mn,Vc,Int>(const Board& board, const Square sq, const Man mn)
		: board(&board), square(sq), man(mn), i(8) {

		this->me().increment();
	}

	void increment() {
		if ( 0 == this->i ) {
			this->i = -1;
			return;
		}

		--this->i;
		const SquareVector v = man.isKnight()
			? this->KNIGHT_VECTORS()[this->i]
			: this->KING_VECTORS()[this->i];

		this->attack = this->square + v;

		if ( !this->me_c().isValid() )
			this->me().increment();
	}

	bool equal(LeaperAffectVec const& other) const {
		return this->i == other.i;
	}

	const Square dereference() const {
		return this->attack;
	}

protected:
	bool isValid() const;
protected:
	const Board* board;
	Square square;
	Man man;
	Square attack;
	Int i;

};

#endif /* LEAPERAFFECTVECABSTRACT_H_ */
